package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"time"
)

//文件分段下载
//文件分段上传
//文件分段传输 消费tasker 即可完成 任务 流水线 八台信息
// 其实本身go就是在网络 传输 tcp,ip Fenduan 并发 协作 gorutine 安排 云容器 分发 合作世界的安排就是这样方式处理的
//
func fileChunckedDownload(filename string) {
	file, _ := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
	fileinfo, _ := file.Stat()
	fmt.Println(fileinfo.Size())
	index := 0
	for {
		by := make([]byte, 1024*10)
		n, err := file.Read(by)
		if err != nil && err != io.EOF {
			panic(err.Error())
		}
		if n == 0 {
			break
		}
		index++
		imagepath := fmt.Sprintf("image_%d.png", index)
		ioutil.WriteFile(imagepath, by, 0666)
	}
}
func main() {
	r := gin.New()
	r.Use(func(context *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				context.AbortWithStatusJSON(400, gin.H{"err": err})
			}
		}()
		context.Next()
	})
	r.GET("/", func(c *gin.Context) {
		c.Writer.Header().Set("Content-Type", "image/png;charset=utf-8")
		c.Writer.Header().Set("Transfer-Encoding", "chunked")
		for i := 1; i <= 13; i++ {
			filepath := fmt.Sprintf("image_%d.png", i)
			ctx, _ := ioutil.ReadFile(filepath)
			c.Writer.Write(ctx)
			c.Writer.(http.Flusher).Flush()
			time.Sleep(time.Microsecond)
		}
	})
	log.Fatal(r.Run(":8080"))

}
